<template>
  <el-row>
    <el-col :span="24">
      <el-form :model="job" :rules="rules" ref="job" label-width="100px" :inline="true" class="formstyle">
        <el-row>
            <el-col :span="8">
              <el-form-item label="任务组名称" prop="title">
                <el-input v-model="job.title"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button type="primary" @click="submitForm()" :load="saving">创建</el-button>
                <el-button @click="resetForm()">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="说明" prop="description">
                <el-input type="textarea" v-model="job.description" rows="4" cols="120"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item prop="beginTime" label="开始时间" required>
                <el-date-picker v-model="job.beginTime" type="datetime" placeholder="选择日期时间" :disabled="hasStreaming"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运行周期" prop="cycle">
                <el-input v-model="job.cycle" placeholder="单位 ms" :disabled="hasStreaming"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
    </el-col>
    <el-col :span="24" align="center">
      <el-button type="primary" @click="groupvIsible = true">添加子任务</el-button>
    </el-col>
    <el-col :span="24" align="center">
      <el-table :data="job.group" border size="small" style="width: 90%; margin-top: 10px">
        <el-table-column label="顺序" prop="id" width="60"></el-table-column>
        <el-table-column width="80" label="移动">
          <template slot-scope="scope">
            <i class="el-icon-caret-top my-icon-btn" title="上移" @click="handleUp(scope.$index, scope.row)"></i>
            <i class="el-icon-caret-bottom my-icon-btn" title="下移" @click="handleDown(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column label="任务" prop="title" width="120"></el-table-column>
        <el-table-column label="说明" prop="description" width="240"></el-table-column>
        <el-table-column label="类型" prop="type" width="80"></el-table-column>
        <el-table-column label="参数" prop="args">
          <template slot-scope="scope">
            {{ JSON.stringify(scope.row.args).substr(0,220) }}
          </template>
        </el-table-column>
        <el-table-column width="80" label="操作">
          <template slot-scope="scope">
            <i class="el-icon-edit my-icon-btn" title="修改" @click="handleEdit(scope.$index, scope.row)"></i>
            <i class="el-icon-delete my-icon-btn" title="删除" @click="handleDel(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
      </el-table>

      <!-- 增加子任务弹窗 -->
      <group-job :visible.sync="groupvIsible" :next="nextId" v-on:add="addGroup"></group-job>
      <el-dialog :title="`修改子任务 # ${row.id}`" :visible.sync="editVisible" width="60%" top="8vh" append-to-body>
        <group-job-edit :visible.sync="editVisible" :row="row" v-on:edit="editGroup"></group-job-edit>
      </el-dialog>
    </el-col>
  </el-row>
</template>
<style>
  .formstyle {
    padding: 10px 50px 5px 50px
  }
</style>
<script>
  import groupJob from './group-job'
  import groupJobEdit from './group-job-edit'

  export default {
    data() {
      return {
        groupvIsible: false,
        editVisible: false,
        saving: false,
        chooseRow: 0,
        hasStreaming: false,
        row: {
          type: 'spark',
          args: '{}',
          file: '',
          options: ''
        },
        job: {
          title: '',
          beginTime: new Date(),
          description: '',
          cycle: 24 * 3600000,
          group: [],
        },
        rules: {
          title: [
            { required: true, message: '请输入任务名称', trigger: 'blur' },
          ],
          beginTime: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
          cycle: [
            { required: true, message: '运行周期必须为数字', trigger: 'change' },
          ],
          description: [
            { message: '', trigger: 'blur' },
          ]
        }
      };
    },
    methods: {
      submitForm() {
        this.$refs['job'].validate(async (valid) => {
          if (valid && this.checkStreaming()) {
            let result = await this.$api.call({
              service: 'addjob',
              body: this.job,
              load: {
                context: this,
                name: 'saving'
              }
            })
            this.$message.success('添加成功')
            this.$emit('add', Object.assign({_id: result._id, status: '1'}, this.job))
            this.resetForm()
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      checkStreaming () {
        if (this.job.group && this.job.group.length){
          let streamingCount = this.job.group.filter(x => {return x.type === 'streaming'}).length
          if (streamingCount === 1) {
            this.hasStreaming = true
            if (this.job.group[this.job.group.length - 1].type !== 'streaming') {
              this.$message.error('streaming 任务必须为最后一个运行！')
              return false
            }else{
              return true
            }
          } else if (streamingCount > 1) {
            this.$message.error('最多只能包含一个 streaming 任务')
            this.hasStreaming = true
            return false
          }
        }
        this.hasStreaming = false
        return true
      },
      resetForm() {
        this.$refs['job'].resetFields()
        this.$set(this.job, 'group', [])
        this.hasStreaming = false
      },
      addGroup (groupjob) {
        this.job.group.push(groupjob)
        this.orderGroup()
        this.checkStreaming()
      },
      editGroup () {
        Object.assign(this.job.group[this.chooseRow], this.row)
        this.checkStreaming()
      },
      handleDel (index, row) {
        this.job.group.splice(index, 1)
        this.orderGroup()
      },
      handleEdit (index, row) {
        this.editVisible = true
        Object.assign(this.row, row)
        this.chooseRow = index
        this.row.args = JSON.stringify(this.row.args, null, 2)
      },
      handleUp (index, row) {
        if (index > 0) {
          let tmpRow = this.job.group[index]
          this.$set(this.job.group, index, this.job.group[index - 1])
          this.$set(this.job.group, index - 1, tmpRow)
          this.orderGroup()
          this.checkStreaming()
        }
      },
      handleDown (index, row) {
        if (index < this.job.group.length - 1) {
          let tmpRow = this.job.group[index]
          this.$set(this.job.group, index, this.job.group[index + 1])
          this.$set(this.job.group, index + 1, tmpRow)
          this.orderGroup()
          this.checkStreaming()
        }
      },
      orderGroup () {
        this.job.group.forEach((v, i) => v.id = i + 1)
      }
    },
    computed: {
      nextId () {
        return this.job.group.length + 1
      }
    },
    components: {
      groupJob, groupJobEdit
    }
  }
</script>